<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text"><br>
    <span>AAAA</span>
    <button onclic>看不清换一张</button>
    <script>
        let ipt = document.querySelector('input')
        let span = document.querySelector('span')
        let btn = document.querySelector('button')
        //queryCode获取四位随机的验证码，放到指定的盒子中
        function queryCode() {
            let area = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
            let result = ""
            for (let i = 0; i < 4; i++) {
                //每一次循环都获取一个随机的数字索引 0~61
                let san = Math.round(Math.random() * (61 - 0) + 0)
                //再根据获取的索引从范围字符串找到对应的字符，把找到字符拼接到最后的结果中
                result += area.charAt(san)

            }
            span.innerHTML = result
        }

        //第一次加载页面需要随机的四位数验证码
        queryCode()
        //按钮点击形成新的验证码
        btn.onclick = queryCode

        //离开文本框,判断输入的验证码一直不一致
        ipt.onblur = function () {
            let val = ipt.value
            let code = span.innerHTML
            if (val.toLowerCase() == code.toLowerCase()) {
                alert('输入成功')
            } else {
                alert('验证失败，请重新输入')
                ipt.value = ''
                queryCode()
            }
        }

    </script>
</body>

</html>